package com.tct.ndocgen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tct.ndocgen.entity.KeyConfig;
import com.tct.ndocgen.entity.Rs;
import com.tct.ndocgen.entity.enums.RsEnum;
import com.tct.ndocgen.service.IKeyConfigService;
import com.tct.ndocgen.util.RsUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/8/13.
 */
@RestController
@RequestMapping("/key")
public class KeyController {

    @Value("${upload.save-path}")
    private String savePath;

    @Autowired
    private IKeyConfigService keyConfigService;

    @PostMapping("/add")
    public Rs add(@RequestBody KeyConfig keyConfig) throws IOException {
        int file_name = keyConfigService.count(new QueryWrapper<KeyConfig>().eq("file_name", keyConfig.getFileName()+".ini"));
        if(file_name>0){
            return RsUtil.error(RsEnum.SYSTEM_ERROR,"配置文件名称冲突，请更换配置文件名称");
        }
        String fileName = keyConfig.getFileName()+".ini";
        keyConfig.setFileName(fileName);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        File filePath = new File(savePath+uuid+"-"+fileName);
        if(!filePath.exists()){
            boolean mkdir = filePath.createNewFile();
            if(!mkdir){
                RsUtil.error(RsEnum.SYSTEM_ERROR,"创建文件失败");
            }
        }
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        keyConfig.setCreateTime(time);
        keyConfig.setFilePath(filePath.getPath());
        keyConfigService.save(keyConfig);
        return RsUtil.success("保存成功");
    }

    @PostMapping("/del")
    public Rs del(@RequestBody KeyConfig keyConfig) throws IOException {
        String filePath = keyConfig.getFilePath();
        keyConfigService.removeById(keyConfig.getId());
        FileUtils.delete(new File(filePath));
        return RsUtil.success("删除成功");
    }

    @PostMapping("/set")
    public Rs set(@RequestBody KeyConfig keyConfig) throws IOException {
//        PrintWriter writer = new PrintWriter(keyConfig.getFilePath(),"UTF-8");
//        writer.write(keyConfig.getContent());
//        writer.flush();
//        writer.close();
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream((keyConfig.getFilePath())), StandardCharsets.UTF_8);
        writer.write(keyConfig.getContent());
        writer.flush();
        writer.close();
        keyConfigService.updateById(keyConfig);
        return RsUtil.success("修改成功");
    }

    @GetMapping("/list")
    public Rs list(){
        List<KeyConfig> list = keyConfigService.list();
        return RsUtil.success("加载成功",list);
    }

    @GetMapping("/getContent")
    public Rs getContent(Integer id) throws IOException {
        KeyConfig byId = keyConfigService.getById(id);
        String filePath = byId.getFilePath();
        String content = getContent(filePath);
        return RsUtil.success("查询成功",content);
    }

    public String getContent(String filePath) throws IOException {
        FileInputStream in = new FileInputStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(in);
        byte[] buffer = new byte[1024];
        int bytesRead;
        StringBuilder result = new StringBuilder();
        while ((bytesRead = bis.read(buffer)) != -1) {
            String temp = new String(buffer, 0, bytesRead);
            result.append(temp);
        }
        in.close();
        bis.close();
        return result.toString();
    }
}
